$(function() {
	var codeText = document.querySelector('.code-text');
	var codeView = document.querySelector('.code-view');
	var editor = CodeMirror.fromTextArea(codeText, {
		lineNumbers: true, //显示行号
		mode: "text/html",
		matchBrackets: true,
		indentUnit: 4,
		indentWithTabs: true,
		readOnly: false, //!只读
		lineWrapping: 'wrap', //长行文字换行
		//theme: 'darcula', //皮肤
	});
	editor.setSize('100%', $('.code-text-w').height());
	$(window).resize(function() {
		editor.setSize('100%', $('.code-text-w').height());
	});
	
	var codeViewW = (codeView.contentWindow) ? codeView.contentWindow : (codeView.contentDocument.document) ? codeView.contentDocument.document : codeView.contentDocument;

	var refreshFn = function(res) {
		codeViewW.document.open();
		codeViewW.document.write(res);
		codeViewW.document.close();

		codeText.innerHTML = res
		editor.setValue(res);
	};

	$('.tab-group').on('click', 'a', function(event) {
		event.preventDefault();
		$(this).addClass('active').siblings().removeClass('active');

		$.get($(this).attr('href'), function(res) {
			refreshFn(res);
		});
	});

	$('.run').on('click', function() {
		refreshFn(editor.getValue());
	});
})